package util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class DBUtil {
	private static Logger logger = Logger.getLogger(DBUtil.class);
	
	public static void error(SQLException e){
		logger.error("数据库操作异常", e);
	}
	
	// 查询数据方法
	public static String[] queryOne(String sql, Object[] paraArray,int returnColumnCount) throws SQLException {
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement pst = conn.prepareStatement(sql);
		if (paraArray != null) {
			for (int i = 0; i < paraArray.length; i++) {
				pst.setObject(i + 1, paraArray[i]);
			}
		}
		ResultSet rs = pst.executeQuery();
		String[] array = null;
		if (rs.next()) {
			array = new String[returnColumnCount];
			for (int i = 0; i < returnColumnCount; i++) {
				array[i] = rs.getString(i + 1);
			}
		}
		JdbcUtil.release(rs, pst, conn);
		return array;
	}
	
	// 查询数据方法
	public static List<String[]> query(String sql, Object[] paraArray,int returnColumnCount) throws SQLException {
		List<String[]> list = new ArrayList<>();
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement pst = conn.prepareStatement(sql);
		if (paraArray != null) {
			for (int i = 0; i < paraArray.length; i++) {
				pst.setObject(i + 1, paraArray[i]);
			}
		}
		ResultSet rs = pst.executeQuery();
		while (rs.next()) {
			String[] array = new String[returnColumnCount];
			for (int i = 0; i < returnColumnCount; i++) {
				array[i] = rs.getString(i + 1);
			}
			list.add(array);
		}
		JdbcUtil.release(rs, pst, conn);
		return list;
	}

	// 更新数据方法
	public static int update(String sql, Object[] paraArray) throws SQLException {
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement pst = conn.prepareStatement(sql);
		for (int i = 0; i < paraArray.length; i++) {
			pst.setObject(i + 1, paraArray[i]);
		}
		int i = pst.executeUpdate();
		JdbcUtil.release(null, pst, conn);
		return i;
	}
	
}
